package learnonline.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import learnonline.dao.DaoException;
import learnonline.dao.RowMapper;

public class JdbcImpl {
	public Connection openConnection() throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/learnonline", "root", "");
		return conn;
	}

	public void closeResx(ResultSet rs, PreparedStatement stmt, Connection conn) {
		if (rs != null)
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		if (stmt != null)
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		if (conn != null)
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}

	public boolean executeUpdate(String sql, Object... parameters) {

		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			conn = this.openConnection();
			stmt = conn.prepareStatement(sql);
			if (parameters != null) {
				for (int i = 0; i < parameters.length; i++) {
					stmt.setObject(i + 1, parameters[i]);
				}
			}
			stmt.executeUpdate();
			return true;
		} catch (Exception ex) {
			throw new DaoException(ex);
		} finally {
			this.closeResx(null, stmt, conn);
		}
	}

	public <T> List<T> queryList(String sql, RowMapper<T> rowMapper, Object... parameters) {
		List<T> list = new ArrayList<T>();
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			conn = this.openConnection();
			stmt = conn.prepareStatement(sql);
			if (parameters != null) {
				for (int i = 0; i < parameters.length; i++) {
					stmt.setObject(i + 1, parameters[i]);
				}
			}
			rs = stmt.executeQuery();
			while (rs.next()) {
				T t = rowMapper.mapRow(rs);
				list.add(t);
			}
			return list;
		} catch (Exception ex) {
			throw new DaoException(ex);
		} finally {
			this.closeResx(rs, stmt, conn);
		}
	}

}
